import store from '../store'
import { getSongUrl } from '@/api/music.js'

let innerAudioContext = uni.createInnerAudioContext()
// innerAudioContext.autoplay = false;

export default {
	
	changeMusic(id) {	//切歌并开始播放
		if(id != '' && id != undefined) {
			getSongUrl(id).then(res => {	//获取歌曲url
				store.commit('changeCurrentMusicUrl', res.data[0].url)
				innerAudioContext.destroy()
				innerAudioContext = uni.createInnerAudioContext()
				this.playMusic()
			}) 
		} else {
			this.setMusicPlayingTime(store.state.currentPlayTime)
			this.playMusic()
		}	
	},
	
	playMusic() {	//音乐播放器实例
		innerAudioContext.src = store.state.currentMusicUrl
		// innerAudioContext.seek(270)
		innerAudioContext.loop = store.state.playMode == 'singleLoop' ? true : false
		store.state.isPlayingMusic ? innerAudioContext.play() : innerAudioContext.pause()
		innerAudioContext.onPlay(() => {
			console.log('---------开始播放---------');
			let playingTime = setInterval(() => {	//持续更新当前歌曲的播放时间
				store.commit('changeCurrentPlayTime', this.getCurrentPlayTime())
			},500)
		});
		innerAudioContext.onCanplay(() => {
			console.log('---------歌曲已就绪---------');
			this.getCurrentMusicLong()
		});
		innerAudioContext.onPause(() => {
			console.log('---------暂停播放---------');
		});
		innerAudioContext.onEnded(() => {
			console.log('---------播放完毕---------')
			this.getNextMusic()
		})
		innerAudioContext.onError((res) => {
			console.log(res.errMsg);
			console.log(res.errCode);
		});
	},
	
	getNextMusic() {	//根据当前的播放模式获取下一首歌曲的id,vuex中的歌曲id改变后即可自动播放
		let musicId = ''
		if(store.state.playMode == 'loop') {	//列表循环
			innerAudioContext.loop = false
			let index = store.state.currentPlayList.findIndex(item => item.id == store.state.currentMusicId)
			if(index == -1) {	//如果当前播放的歌曲不在播放列表中，则随机挑一首歌播放
				innerAudioContext.loop = false
				let rd = Math.floor(Math.random()*(store.state.currentPlayList.length - 1))
				musicId = store.state.currentPlayList[rd].id
				console.log(rd, musicId)
				store.commit('changeCurrentMusicId', musicId)
				return
			}
			if(index != store.state.currentPlayList.length - 1) {
				musicId = store.state.currentPlayList[index + 1].id
				store.commit('changeCurrentMusicId', musicId)
			} else {
				musicId = store.state.currentPlayList[0].id
				store.commit('changeCurrentMusicId', musicId)
			}
		} else if(store.state.playMode == 'random') {	//随机播放
			innerAudioContext.loop = false
			let rd = Math.floor(Math.random()*(store.state.currentPlayList.length - 1))
			musicId = store.state.currentPlayList[rd].id
			store.commit('changeCurrentMusicId', musicId)
		} else if(store.state.playMode == 'singleLoop') {	//单曲循环
			innerAudioContext.loop = true
		}
	},
	
	getCurrentPlayTime() {	//获取当前播放进度
		return innerAudioContext.currentTime
	},
	
	setMusicPlayingTime(time) {		//拖动播放进度条时改变播放进度
		innerAudioContext.seek(time)
	},
	
	getCurrentMusicLong() {		//获取当前歌曲总时长
		setTimeout(() => {
			store.commit('changeCurrentMusicLong', innerAudioContext.duration)
		}, 1000)
	}
}